<?php
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use think\facade\Db;
//公共函数文件

//统一成功返回
function success($msg = '', $data = null)
{
    return json([
        'code' => 1,
        'msg' => $msg,
        'data' => $data
    ]);
}
//统一失败返回
function error($msg = '', $data = null)
{
    return json([
        'code' => 1,
        'msg' => $msg,
        'data' => $data
    ]);
}

//生成随机字符串
function createRandStr($length = 8)
{
    $str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randStr = '';
    for($i = 0;$i < $length;$i++){
        $randStr .=$str[mt_rand(0,35)];
    }
    return $randStr;
}
//生成TOKEN
function signToken($userId,$mobile){
    $data = [
        //签发人
        'iss' => request()->domain(),
        //签发时间
        'iat' => time(),
        //自定义数据
        'data' => [
            'user_id' => $userId,
            'mobile' => $mobile,
        ],
    ];
    $key = config('app.jwt_key');
    $token = \Firebase\JWT\JWT::encode($data,$key, 'HS256');
    return $token;
}
//验证码
function sendAliSms($mobile)
{
    $code = mt_rand(1111,9999);

    $config = new Config([
        // 从阿里云获取
        'accessKeyId' => config('app.aliSms.accessKeyId'),
        'accessKeySecret' => config('app.aliSms.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = '阿里云短信测试';
    // 模板CODE
    $sendSmsRequest->templateCode = 'SMS_154950909';
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    if ($response->body->code == 'OK') {
        Db::name('sms_code_log')->insert([
            'code' => $code,
            'mobile' => $mobile,
            'send_time' => time()
        ]);
        return ['code' => 1,'msg' => '短信发送成功'];//'短信发送成功！';
    }else{
        return ['code' => 0,'msg' => $response->body->message];
    }
}
//验证验证码
function checkSmsCode($mobile,$code){
    $log = \think\facade\Db::name('sms_code_log')
        ->where('mobile',$mobile)
        ->find();

    if(!$log) {
        return false;
    }
    if($log['code'] != $code) {
        return false;
    }
    if(time() - $log['send_time'] > 60) {
        //删除
        Db::name('sms_code_log')->where('mobile','=',$mobile)->delete();
        return false;
    }
    //删除
    Db::name('sms_code_log')->where('mobile',$mobile)->delete();
    return true;
}